$(document).ready(function($) {
	$.extend({
		pageConfig:{
			appName:"",
			dataTable:null
		},
		sweetalert2:{
			alert:function (msg) {
				return Swal.fire({position: "top",title: msg,confirmButtonText: "关闭",width:"23em",allowOutsideClick: false});
			}
		},
		tree:{
			treeId:"menuTree",
			treeObj:"",
			setting: {
				view: {dblClickExpand: true,fontCss:{'color':'#676a6c','font-weight':'bold'}},
				check: {enable: true},
				data: {simpleData: {enable: true,idKey : "id",pIdKey : "parentId"},key:{name:"menuName"}},
				edit:{enable: false,editNameSelectAll: true,showRemoveBtn : true, showRenameBtn : true,
					removeTitle : "删除",renameTitle : "重命名"
				}
			},
			formTree:function(url,params,extParam){
				$.ajax({type: "POST",dataType: "json",url:url,data:params,
					success: function (data) {
						if(data.success){
							var zTree = $.fn.zTree.init($("#"+$.tree.treeId), $.tree.setting, data.data.menus);
							$.tree.treeObj = zTree;

							var menuIds = data.data.roleMenuIds;
							if(menuIds && menuIds.length>0){
								for(var i = 0; i < menuIds.length; i++) {
									var node = zTree.getNodeByParam("id", menuIds[i].menuId);
									if(node != null) {
										zTree.checkNode(node, true);
										if(node.hasOwnProperty("getParentNode")){
											$.tree.checkedPatent(node.getParentNode());
										}
									}
								}
							}

							zTree.expandAll(true);

							if(extParam){
								var node = zTree.getNodeByParam("id", extParam);
								zTree.setChkDisabled(node, true);
							}
						}else{
							$.sweetalert2.alert(data.msg);
						}
					},
					error: function(data) {
						$.sweetalert2.alert("ajax error");
					}
				});
			},
			checkedPatent:function(node){
				if(node && !node.checked){
					this.treeObj.checkNode(node, true);
					if(node.hasOwnProperty("getParentNode")){
						this.checkedPatent(node.getParentNode());
					}
				}
			},
			getCheckedResult:function(checked){
				var checkedNodes = this.treeObj.getCheckedNodes(checked);
				var shtml = "";
				if(checkedNodes && checkedNodes.length>0){
					for(var i = 0; i < checkedNodes.length; i++) {
						shtml += checkedNodes[i].id + ",";
					}
				}
				return shtml;
			}
		},
		modal:{
			myModal:{},
			formSign:"",
			modalSettings:{
				modalSize:"",
				formLabelClass:"col-md-2",
				formInputClass:"col-md-10",
				slimScroll:{},
			},
			initModal:function (modal) {
				this.formSign = "";
				$(".modal-submit").attr("disabled",false);
				this.myModal=modal;
				this.myModal.modalBody=modal.find(".modal-body");
				this.myModal.find(".modal-title,.small-title").text("").end().modal('show');

				return this;
			},
			initSettings:function(settings){
				this.myModal.find(".modal-dialog").removeClass(this.modalSettings.modalSize);
				this.modalSettings.modalSize = settings.modalSize;
				this.modalSettings.formLabelClass = settings.formLabelClass;
				this.modalSettings.formInputClass = settings.formInputClass;
				this.myModal.find(".modal-dialog").addClass(this.modalSettings.modalSize);
				if(settings.slimScroll){
					this.myModal.modalBody.slimScroll(settings.slimScroll);
				}else{
					this.myModal.modalBody.slimScroll({"destroy":true});
					this.myModal.modalBody.attr('style', '');
				}
				return this;
			},
			addModalTitle:function (title) {
				this.myModal.find(".modal-title").text(title);
				return this;
			},
			addModalSmallTitle:function (title) {
				this.myModal.find(".small-title").text(title);
				return this;
			},
			addModalTable:function (columnInfo) {
				$("#modal-table").dataTable().draw();
				var shtml = "";
				shtml += ' <table id="modal-table" class="table table-bordered table-hover table-striped w-100"> ';
				if(columnInfo && columnInfo.length){
					shtml += ' 	<thead><tr> ';
					for(var i=0;i<columnInfo.length;i++){
						shtml += ' 	<th>'+columnInfo[i]+'</th> ';
					}
					shtml += ' 	</tr></thead> ';
				}else{
					return ;
				}
				shtml += ' 	<tbody> ';
				shtml += ' 	</tbody> ';
				shtml += ' </table> ';
				this.myModal.modalBody.empty().append(shtml);
				return this;
			},
			addModalForm:function (action,method) {
				this.myModal.modalBody.empty().append('<form action="'+action+'" method="'+method+'"></form>');
				return this;
			},
			addModalFormNode:function (data) {
				var title = data.title;
				var node = data.node;
				var shtml = "";
				shtml += '<div class="row input-modal">';
				shtml += '	<label class="'+this.modalSettings.formLabelClass+' control-label">'+title+'</label>';
				shtml += '	<div class="'+this.modalSettings.formInputClass+'">'+node+'</div> ';
				shtml += '</div>';
				this.myModal.modalBody.find("form").append(shtml);
				return this;
			},
			addModalFormInput:function (data) {
				var shtml = "";
				if("hidden"==data.type){
					shtml += '	<input type="'+data.type+'" name="'+data.name+'" value="'+data.value+'" ';
					shtml += '	class="form-control" placeholder="'+data.msg+'"> ';
				}else{
					shtml += '<div class="row input-modal">';
					shtml += '	<label class="'+this.modalSettings.formLabelClass+' control-label">'+data.title+'</label>';
					shtml += '	<div class="'+this.modalSettings.formInputClass+'"><input type="'+data.type+'" name="'+data.name+'" value="'+data.value+'" ';
					shtml += '	class="form-control" placeholder="'+data.msg+'" '+data.property+'></div> ';
					shtml += '</div>';
				}
				this.myModal.modalBody.find("form").append(shtml);
				return this;
			},
			addModalFormOption:function (data) {
				var options = data.options;

				var optionValues = "";
				if(data.optionValues){
					optionValues= data.optionValues.split(",");
				}

				var shtml = "";
				shtml += '<div class="row input-modal">';
				shtml += '	<label class="'+this.modalSettings.formLabelClass+' control-label">'+data.title+'</label>';
				shtml += '	<div class="'+this.modalSettings.formInputClass+'">';
				shtml += '	<select class="'+data.name+' form-control" name="'+data.name+'" '+(data.multiple?'multiple':'')+' > ';
				if(data.allowNull){
					shtml += '	<option value=""  ></option> ';
				}
				for(var i=0;i<options.length;i++){
					shtml += '	<option value="'+options[i][data.valueKey]+'" '+((optionValues && optionValues.indexOf(''+options[i][data.valueKey])>-1)?'selected':'')+'  >'+options[i][data.textKey]+'</option> ';
				}

				shtml += '	</select> ';
				shtml += '	</div> ';
				shtml += '</div>';
				this.myModal.modalBody.find("form").append(shtml);
				$('.'+data.name).select2({dropdownParent: this.myModal,
					placeholder: "请选择",
					allowClear: true
				});

				return this;
			},
			addModalFormCheckBox:function (data) {
				var shtml = "";
				var boxes = data.checkboxData;

				var checkedData;
				if(data.checkedValues!=""){
					checkedData = data.checkedValues.split(",");
				}

				if(boxes.length>0){
					shtml += '<div class="row" style="margin-top: 10px">';
					shtml += '	<label class="'+this.modalSettings.formLabelClass+' control-label" style=" text-align: center;">'+data.title+'</label>';
					shtml += '	<div class="'+this.modalSettings.formInputClass+'">';

					for(var i=0;i<boxes.length;i++){
						shtml += '<div class="custom-control custom-checkbox custom-control-inline" style="margin-bottom: 5px">';
						shtml += '<input type="checkbox" class="custom-control-input"  ';
//	                    if(boxes[i][data.disabledKey]!=0){
//	                    	shtml += ' disabled ';
//	                    }
						if(checkedData && checkedData.indexOf(''+boxes[i][data.valueKey])>-1){//数组是否包含区分数字和字符串
							shtml += ' checked ';
						}
						shtml += '   id="checkbox-'+data.name+boxes[i][data.valueKey]+'" name="'+data.name+'" value="'+boxes[i][data.valueKey]+'">';
						shtml += '   <label class="custom-control-label" for="checkbox-'+data.name+boxes[i][data.valueKey]+'">'+boxes[i][data.textKey]+'</label>';
						shtml += '</div>';
					}

					shtml += '	</div>';
					shtml += '</div>';

				}
				this.myModal.modalBody.find("form").append(shtml);

				return this;
			},
			formSubmit:function() {
				if(!this.formSign){
					this.formSign = $.common.uuid();
					$(".modal-submit").attr("disabled",true);
					this.myModal.find("form").submit();
				}
			},
			ajaxSubmit:function(returnUrl) {
				var submitForm = this.myModal.find("form");
				if(!this.formSign){
					this.formSign = $.common.uuid();
					$(".modal-submit").attr("disabled",true);
					$.ajax({
						type: "POST",dataType: "json",url:submitForm.attr("action"),data:submitForm.serialize(),
						success: function (data) {
							if(data.success){
								if(returnUrl){
									location.href= returnUrl;
								}else if(data.msg){
									$.sweetalert2.alert(data.msg);
								}
							}else{
								$.sweetalert2.alert(data.msg);
							}
							$.modal.formSign = "";
							$(".modal-submit").attr("disabled",false);
						},
						error: function(data) {
							$.sweetalert2.alert("ajax error");
							$.modal.formSign = "";
							$(".modal-submit").attr("disabled",false);
						}
					});
				}
			},
			ajaxSubmit2:function(fun) {
				var submitForm = this.myModal.find("form");
				if(!this.formSign){
					this.formSign = $.common.uuid();
					$(".modal-submit").attr("disabled",true);
					$.ajax({
						type: "POST",dataType: "json",url:submitForm.attr("action"),data:submitForm.serialize(),
						success: function (data) {
							fun(data);
							$.modal.formSign = "";
							$(".modal-submit").attr("disabled",false);
						},
						error: function(data) {
							$.sweetalert2.alert("ajax error");
							$.modal.formSign = "";
							$(".modal-submit").attr("disabled",false);
						}
					});
				}
			}
		},
		common:{
			ajaxPostJson:function (url,data,sucFn) {
				$.ajax({
					type: "POST",dataType: "json",url:url,data:data,
					success: function (data) {
						sucFn(data);
					},
					error: function(data) {
						$.sweetalert2.alert("ajax error");
					}
				});
			},
			ajaxPostJsonSuc:function (url,data,sucFn) {
				$.common.ajaxPostJson(url,data,function (data) {
					if(data.success){
						sucFn(data);
					}else{
						$.sweetalert2.alert(data.msg);
					}
				});
			},
			uuid:function () {
				var s = [];
				var hexDigits = "0123456789abcdef";
				for (var i = 0; i < 36; i++) {
					s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
				}
				s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
				s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
				s[8] = s[13] = s[18] = s[23] = "-";

				var uuid = s.join("");
				return uuid;
			},
			isJSON: function (str) {
				if (typeof str == 'string') {
					try {
						var obj = JSON.parse(str);
						if (obj && typeof obj == 'object') {
							return true;
						} else {
							return false;
						}
					} catch (e) {
						return false;
					}
				}
				return  false;
			}
		},
		operation:{
			operations:[],
			resolveExpression:function(name,row) {
				if(name){
					if(name.startsWith("{") && name.endsWith("}")){
						var obj = JSON.parse(name);
						if (obj && typeof obj == 'object') {
							var key = obj.key.trim(),result = obj.result,trueResult = obj.trueResult.trim();
							if(row[key]==result){
								return trueResult;
							}else if(obj.hasOwnProperty("falseResult")){
								return obj.falseResult.trim();
							}else{
								return false;
							}
						}
					}else{
						return name;
					}
				}
			},
			initOperation:function(row,location) {
				var shtml = "";
				for(var i=0;i<this.operations.length;i++){
					var nowOperation = this.operations[i];
					if(nowOperation.location==location){
						var name = this.resolveExpression(nowOperation.name,row);
						if(name){
							if(nowOperation.optionType==1){//按钮
								shtml += ' <button '+nowOperation.attach+' class="'+this.resolveExpression(nowOperation.classStyle,row)+'"  data-url="'+nowOperation.dataUrl+'"> ';
								if(nowOperation.icon){
									shtml += nowOperation.icon;
								}
								shtml += name;
								shtml += ' </button> ';
							}else if(nowOperation.optionType==2){//直接跳转的超链接
								var dataUrl = $.pageConfig.appName+nowOperation.dataUrl;
								if(location==3){
									dataUrl += '?id='+row.id;
								}
								shtml += ' <a ';
								if(nowOperation.isConfirm==1){
									shtml += ' href="javascript:void(0);" class="'+this.resolveExpression(nowOperation.classStyle,row)+' btn-sweetalert2'+'"';
								}else{
									shtml += ' href="'+dataUrl+'" class="'+this.resolveExpression(nowOperation.classStyle,row)+'"';
								}
								shtml += ' data-url="'+dataUrl+'" '+nowOperation.attach;
								shtml +=' >';
								if(nowOperation.icon){
									shtml += nowOperation.icon;
								}
								shtml += name;
								shtml += ' </a> ';
							}else if(nowOperation.optionType==3){
								shtml += nowOperation.attach;
							}
						}
					}
				}
				if(!shtml && location==3){
					shtml = "-";
				}
				return shtml;
			}
		}
	});

	// $('.input-modal input').attr("readonly","readonly");//让from表单下所有的input输入框都是只读状态(#setaccount是方法2里面from表单的id)

	// $(document).on('click', '.input-modal input',function(event) {
	// 	$(this).removeAttr("readonly");
	// });

	// $(".btn-operate:not(.btn-checkbox-0)").attr("disabled",true);
	$(".btn-checkbox-1,.btn-checkbox-2").attr("disabled",true);

	$(document).on('page.dt', 'table.table',function(event) {
		$("#select-all,.select-one").prop("checked",false);
		$(".btn-checkbox-1,.btn-checkbox-2").attr("disabled",true);
	});

	$(document).on('click', '#select-all',function(event) {
		$(".select-one").prop("checked",this.checked);
		$("#select-all").parent().removeClass("checked-some");
		resetBtnAbled();
	});

	$(document).on('click', '.select-one',function(event) {
		if($(".select-one:checked").length>0){
			$("#select-all").prop("checked",true);
			if($(".select-one:checked").length==$(".select-one").length){
				$("#select-all").parent().removeClass("checked-some");
			}else{
				$("#select-all").parent().addClass("checked-some");
			}
		}else{
			$("#select-all").parent().removeClass("checked-some");
			$("#select-all").prop("checked",false);
		}
		resetBtnAbled();
	});

	$(document).on("show.bs.modal", ".modal", function () {
		$('.modal-dialog').draggable();
		$(this).css("overflow", "hidden");
		// 不拖动透明背景
	});

	var resetBtnAbled = function(){
		if($(".select-one:checked").length>0){
			$(".btn-checkbox-1,.btn-checkbox-2").attr("disabled",false);
			if($(".select-one:checked").length>1){
				$(".btn-checkbox-1").attr("disabled",true);
			}
		}else{
			$(".btn-checkbox-1,.btn-checkbox-2").attr("disabled",true);
		}
	}

	$(document).click(function() {
		parent.$(window.parent.document).find("body").trigger("click");
	});

	$(document).on('click', '.btn-reset',function(event) {
		$(".form-param").val("");
		$(".select2-search").empty();
		$('#date-range').val('选择时间');

	});

	$(document).on("click", '.btn-sweetalert2',function(){
		var url = $(this).attr("data-url");
		Swal.fire({
			title: "确定"+$(this).text().trim()+"["+$(this).parent().siblings().eq(0).find("input").attr("data-name")+"]吗?",text: "",type: "warning",
			showCancelButton: true,cancelButtonText: "取消",confirmButtonText: "确定",reverseButtons: true
		}).then(function(result){
			if(result.value){
				location.href = url;
			}
		});
	});

	$(document).on("change", '.input-upload',function(){
		var fileList=this.files,alertMsg = "",check = false,uploadFile = null,importUrl = $(this).attr("data-url");
		if(fileList.length>0){
			uploadFile = fileList[0];
			if(uploadFile.name.endsWith(".xls") || uploadFile.name.endsWith(".xlsx")){
				alertMsg = "确定导入"+uploadFile.name.trim()+"吗？";
				check = true;
			}else{
				alertMsg = "请选择excel导入文件";
			}
		}else{
			alertMsg = "请选择导入文件";
		}

		Swal.fire({
			title: alertMsg,text: "",type: "warning",
			showCancelButton: true,cancelButtonText: "取消",confirmButtonText: "确定",reverseButtons: true
		}).then(function(result){
			if(check && result.value){//文件上传
				var formData = new FormData();
				var name = $("#importFile").val();
				formData.append('file', uploadFile);
				// 此处可传入多个参数
				formData.append('name', uploadFile.name);
				$.ajax({
					url:  $.pageConfig.appName + importUrl,
					type: 'post',
					async: false,
					data: formData,
					processData: false,// 告诉jQuery不要去处理发送的数据
					contentType: false,// 告诉jQuery不要去设置Content-Type请求头
					dataType: "json",
					beforeSend: function () {//过程...
						console.log('正在进行，请稍候')
					},
					success: function (result) {
						if(result.success){
							$.sweetalert2.alert(result.msg);
							$.pageConfig.dataTable.draw();
						}else{
							$.sweetalert2.alert(result.msg);
						}
						$(".input-upload").val(null);
					},
					error:function(){
						$.sweetalert2.alert("客户端异常");
					}
				})
			}else{
				$(".input-upload").val(null);
			}
		});
	});
});


var addCookie = function(name, value, hours){ //修改或是添加cookie
	var expire = "";
	if(hours != null){
		expire = new Date((new Date()).getTime() + hours * 3600000);
		expire = "; expires=" + expire.toGMTString();
	}
	document.cookie = name + "=" + escape(value) + expire;
	//如果指定域名可以使用如下
	//document.cookie = name + "=" + escape(value) + expire + ";path=/;domain=findme.wang";
};

var getCookie = function(c_name){//读取cookie
	if (document.cookie.length>0){
		var c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
			c_start=c_start + c_name.length+1
			c_end=document.cookie.indexOf(";",c_start)
			if (c_end==-1){
				c_end=document.cookie.length
			}
			return unescape(document.cookie.substring(c_start,c_end))
		}
	}
	return "";
}

